jQuery.fn.waiting = function() {
    $(this[0]).html('<img src="/images/ajax-loader.gif"/>');
};

$().ready(function() {
    $('.delete').click(function() {
        return confirm('Are you sure?');
    });

    $('#meta-form :radio').change(function() {
        var div = '#meta-form #params';
        $(div).waiting();
        $.post('/meta/list', {
                    'act' : $(this).val()
                },
                function(data) {
                    $(div).html(data);
                },
                'html')
    });

    $('select').chosen();

    $("#tree").jstree({ "plugins" : ["themes","html_data", "ui", "dnd"],
        "dnd": {
            'drop_finish' : function() {
                console.log('drop finished');
            },

            'drag_check' : function(data) {
                return true;
            },

            'drag_finish' : function(data) {
                console.log('Drag finished');
            }
        }
    })
            .bind("select_node.jstree", function (event, data) {
                var id = data.rslt.obj.attr("id");
                location.href = '/pages/edit/id/' + id;
            })
            .delegate("a", "click", function (event, data) {
                event.preventDefault();
            })
            .bind("move_node.jstree", function (e, data) {
                data.rslt.o.each(function (i) {
                    $.ajax({
                        async : false,
                        type: 'POST',
                        url: "/pages/dnd",
                        data : {
                            "operation" : "move_node",
                            "id" : $(this).attr("id").replace("node_", ""),
                            "ref" : data.rslt.cr === -1 ? 0 : data.rslt.np.attr("id").replace("node_", ""),
                            "position" : data.rslt.cp + i,
                            "title" : data.rslt.name,
                            "copy" : data.rslt.cy ? 1 : 0
                        },
                        success : function (r) {
                            if (!r.status) {
                                $.jstree.rollback(data.rlbk);
                            }
                            else {
                                $(data.rslt.oc).attr("id", "node_" + r.id);
                                if (data.rslt.cy && $(data.rslt.oc).children("UL").length) {
                                    data.inst.refresh(data.inst._get_parent(data.rslt.oc));
                                }
                            }
                            $("#analyze").click();
                        }
                    });
                });
            });

});

